package com.ymatou.iapi.sellerproduct.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ymt.core.tool.Logger;
import com.ymttest.business.YmatouAutoTestCall;
import com.ymttest.business.service.AssertService;
import com.ymttest.business.service.SellerProductCallService;
import com.ymttest.database.model.YmtCatalogsI;
import com.ymttest.database.model.YmtProductsI;
import com.ymttest.database.mongo.ProductBasicInfoWapper;
import com.ymttest.database.mongo.ProductDescriptionInfoWapper;
import com.ymttest.database.mongo.ProductDescriptionModelWapper;
import com.ymttest.database.mongo.ProductDetailModelWapper;
import com.ymttest.database.mongo.ProductListingModelWapper;
import com.ymttest.database.mongo.ProductStockInfoWapper;
import com.ymttest.database.mongo.YmtMongoDriverFactroy;
import com.ymttest.database.sqlwapper.YmtCatalogsIWapper;
import com.ymttest.database.sqlwapper.YmtProductsIWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.MapUtil;
/**
*修改商品信息Call
*FreeMaker Template自动生成代码
*/
public class ChangeNewProductInfoCall extends YmatouAutoTestCall{
	private static String opurl ="/api/SellerProduct/ChangeNewProductInfo";
	
	public ChangeNewProductInfoCall() {
		super(EnvSetup.getSystemUrl("sellerproduct_iapi"),opurl,"POST","JSON");
	}
	@Override
	public void addDefHeader() {
		client.addHeader("Content-Type", "application/json; charset=UTF-8");
	}
	
	public static void main(String[] args) {
		new ChangeNewProductInfoCall().callAndGetReturnData();
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 编辑商品sql & Mongo断言
	 * @param requestBean
	 * @throws Exception
	 */
	public static void checkSQLAndMongo_ModifyProduct(JSONObject requestBean) throws Exception{
		Logger.debug("校验SQL & Mongo");
		JSONObject productBean = requestBean.getJSONObject("Product");
		//取出请求报文的参数
		
		int userId = requestBean.getInt("UserID");
		String productId = requestBean.getString("ProductID");
		
		String productDesc = productBean.getString("MobileDescription");
		int tariffType = productBean.getInt("TariffType");//包税
		int flight = productBean.getInt("Flight");//是否包邮 0为包邮
		boolean noticeRisk = productBean.getBoolean("NoticeRisk");//砍单风险
		int limitedNumber = productBean.getInt("LimitNum");//限购数量
		int localReturn = productBean.getInt("LocalReturn");//退货方式
		String title = productBean.getString("ProductName");
		boolean noReasonReturn = productBean.getBoolean("NoReasonReturn"); //无理由退货
		boolean isNew = productBean.getBoolean("IsNew"); //是否新品
		
		//get pic and check 
		List<String> picList = new ArrayList<String>();
		int maxPicCount = 12;
		for (int i=0;i<maxPicCount;i++){
			if (!productBean.isNull("PictureUrl"+(i+1))){
				picList.add(productBean.getString("PictureUrl"+(i+1)));
			}
		}
		
		
		
		//SQL -Ymt_Products
		YmtProductsI ymtProductsI = new YmtProductsIWapper().selectProductByProductId(productId).get(0);
	
		
		int deliveryMethod = ymtProductsI.getiCatalogStatus();
		
		Map<String, Object> sqltgtMap = new HashMap<String,Object>();
		sqltgtMap.put("iUserId", userId);
		sqltgtMap.put("sProductId", productId);
		sqltgtMap.put("sProduct", title);
		sqltgtMap.put("sMobileDescription", productDesc);
		sqltgtMap.put("iTariffType", tariffType);
		sqltgtMap.put("fFlight", flight);
		sqltgtMap.put("bNoticeRisk", noticeRisk);
		sqltgtMap.put("iLimitNum", limitedNumber);
		sqltgtMap.put("iLocalReturn", localReturn);
		sqltgtMap.put("bNoReasonReturn", noReasonReturn);
		sqltgtMap.put("isNew", isNew?1:0);

		AssertService.assertResultEqual(sqltgtMap, MapUtil.pojoToMap(ymtProductsI),"SQL-Ymt_Products");
		
		//基础项，一层数据检查
		//check Mongo
		if (YmtMongoDriverFactroy.isOldMongoCheck()){
			//ProductBasicInfo
			Map<String, Object> productBasicMap = new ProductBasicInfoWapper().getByProductId(productId);
			
			Map<String, Object> mongoTgtMap = new HashMap<String,Object>();
			mongoTgtMap.put("ProductId", productId);
			mongoTgtMap.put("Name", title);
			mongoTgtMap.put("SellerId", userId);
			mongoTgtMap.put("MobileDescription", productDesc);
			mongoTgtMap.put("TariffType", tariffType);
			mongoTgtMap.put("Freight", flight);
			mongoTgtMap.put("NoticeRisk", noticeRisk);
			mongoTgtMap.put("LimitNum", limitedNumber);
			mongoTgtMap.put("LocalReturn", localReturn);
			mongoTgtMap.put("NoReasonReturn", noReasonReturn);
			
			AssertService.assertResultEqual(mongoTgtMap, productBasicMap,"Mongo-ProductBasicInfo");
			
			
		}
		
		if (YmtMongoDriverFactroy.isNewMongoCheck()){
			//ProductDetailModel
			Map<String, Object> productDetailMap = new ProductDetailModelWapper().getProductId(productId);
			
			Map<String, Object> mongoTgtMap = new HashMap<String,Object>();
			mongoTgtMap.put("ProductId", productId);
			mongoTgtMap.put("Title", title);
			mongoTgtMap.put("Introduction", productDesc);
			mongoTgtMap.put("SellerId", userId);
			mongoTgtMap.put("LimitNum", limitedNumber);
			mongoTgtMap.put("TariffType", tariffType);
			mongoTgtMap.put("Freight", flight);
			mongoTgtMap.put("NoticeRisk", noticeRisk);
			mongoTgtMap.put("LocalReturn", localReturn);
			mongoTgtMap.put("NoReasonReturn", noReasonReturn);
			mongoTgtMap.put("DeliveryMethod", deliveryMethod);
			mongoTgtMap.put("IsNew", isNew);

			AssertService.assertResultEqual(mongoTgtMap, productDetailMap,"Mongo-ProductDetailModel");
			
			//ProductListing
			Map<String, Object> productListMap = new ProductListingModelWapper().getProductId(productId);
			
			AssertService.assertResultEqual(MapUtil.hashMap("Title", title,"TariffType",tariffType,"IsFreeShipping",flight==0?true:false,"DeliveryMethod",deliveryMethod), productListMap,"Mongo-ProductListing");
			
		}
		
		
		
		
		//check picture 
		SellerProductCallService.checkSQLAndMongo_ModifyPicture(productId, picList);
		
		//check ProductDescription
		checkSQLAndMongoDesc(productId,productBean.getJSONObject("ProductDescriptionInfo"));
		
		//check catalogs
		checkSQLAndMongoCatalogs(productId,productBean.getJSONArray("Catalogs"));
		
		
	}
	
	
	
	private static void checkSQLAndMongoDesc(String productId,JSONObject descBean) throws Exception{
		String desc = descBean.getString("WordContent");
		JSONArray picUrls = descBean.getJSONArray("Pictures");	
		
		if (YmtMongoDriverFactroy.isOldMongoCheck()){
			Map<String,Object> productDescriptionInfoMap = new ProductDescriptionInfoWapper().getByProductId(productId);
			String actDesc = productDescriptionInfoMap.get("Description").toString();
			Logger.verifyIsContains(desc, actDesc, "Mongo-ProductDescriptionModel description");
			for(int i=0;i<picUrls.length();i++ ){
				if (picUrls.getJSONObject(i).getInt("Operation") ==1){
					Logger.verifyIsContains(picUrls.getJSONObject(i).getString("PictureUrl"), actDesc, "Mongo-ProductDescriptionInfo description");
				}else{
					Logger.verifyEquals(false,actDesc.contains(picUrls.getJSONObject(i).getString("PictureUrl")), "Mongo-ProductDescriptionInfo description 已删除图片不应保存");
				}
			}
		}
		
		
		if (YmtMongoDriverFactroy.isNewMongoCheck()){
			Map<String,Object> productDescriptionMap = new ProductDescriptionModelWapper().getProductId(productId);
			String actDesc = productDescriptionMap.get("Description").toString();
			Logger.verifyIsContains(desc, actDesc, "Mongo-ProductDescriptionModel description");
			for(int i=0;i<picUrls.length();i++ ){
				if (picUrls.getJSONObject(i).getInt("Operation") ==1){
					Logger.verifyIsContains(picUrls.getJSONObject(i).getString("PictureUrl"), actDesc, "Mongo-ProductDescriptionModel description");
				}else{
					Logger.verifyEquals(false,actDesc.contains(picUrls.getJSONObject(i).getString("PictureUrl")), "Mongo-ProductDescriptionModel description 已删除图片不应保存");
				}
			}
		}
		
	}
	
	//通过product code数量区分规格
	private static void checkSQLAndMongoCatalogs(String productId,JSONArray catalogsBean) throws Exception{
		
		//由于添加删减 catalog 都在报文中，过滤删除catalog的报文（1：新增、2：修改、3：删除、 4：未操作该规格）
		JSONArray newCatalogs = new JSONArray();
		for(int i = 0;i<catalogsBean.length();i++){
			if (catalogsBean.getJSONObject(i).getInt("CatalogOperationType") != 3){
				newCatalogs.put(catalogsBean.getJSONObject(i));
			}
		}
		
		
		
		//Mongo
		YmtCatalogsIWapper ymtCatalogsIWapper = new YmtCatalogsIWapper();
		ProductBasicInfoWapper productBasicInfoWapper= new ProductBasicInfoWapper();
		ProductDetailModelWapper productDetailModelWapper= new ProductDetailModelWapper();
		
		
		int catalogSize = newCatalogs.length();
		Double MaxPrice = (double) -1;
		Double MinPrice = (double) -1;
		
		//SQL Ymt_Catalogs
		List<YmtCatalogsI> ymtCatalogsIList = ymtCatalogsIWapper.selectCatalogsByProductId(productId);
		List<YmtCatalogsI> ymtCatalogsIListAction0 = new ArrayList<YmtCatalogsI>();
		for(YmtCatalogsI y:ymtCatalogsIList){
			if (y.getiAction()==0){
				ymtCatalogsIListAction0.add(y);
			}
		}
		Logger.verifyEquals(catalogSize, ymtCatalogsIListAction0.size(), "SQL-Ymt_Catalogs 规格数量");
		
		//New Mongo - ProductDetailModel
		if (YmtMongoDriverFactroy.isNewMongoCheck()){
			JSONArray CatalogList = new JSONArray(productDetailModelWapper.getProductId(productId).get("CatalogList").toString());
			Logger.verifyEquals(catalogSize, CatalogList.length(), "Mongo-ProductDetailModel CatalogList 规格数量");
		}
		
		
		//遍历catalogList 检查
		for (int i=0;i<catalogSize;i++){
			JSONObject catalogs = newCatalogs.getJSONObject(i);
			Double price = catalogs.getDouble("Price");
			Double vipPrice = catalogs.getDouble("VipPrice");
			//Double earnestPrice = catalogs.getDouble("EarnestPrice"); 定金字段 不维护了
			Double newCustomerPrice = catalogs.getDouble("NewCustomerPrice");
			int numStock = catalogs.getInt("Num");
			String productCode = catalogs.getString("ProductCode");
			String sSKU = catalogs.getString("SKU");
			
			
			//get CatalogId by product code
			String catalogId = "";
			YmtCatalogsI ymtCatalogsI = null;
			for(YmtCatalogsI y:ymtCatalogsIListAction0){
				if (y.getsSKU().equals(sSKU)){
					catalogId = y.getsCatalogId();
					ymtCatalogsI = y;
					break;
				}
			}
			
			//SQL Ymt_Catalogs
			Map<String, Object> sqlTgtMap = new HashMap<String,Object>();
			sqlTgtMap.put("sProductId", productId);
			sqlTgtMap.put("sCatalogId", catalogId);
			sqlTgtMap.put("iNum", numStock);
			sqlTgtMap.put("fQuotePrice", price);
			sqlTgtMap.put("fVipPrice", vipPrice);
			sqlTgtMap.put("fNewCustomerPrice", newCustomerPrice);
			sqlTgtMap.put("sProductCode", productCode);
			sqlTgtMap.put("sSKU", sSKU);
			
			AssertService.assertResultEqual(sqlTgtMap, MapUtil.pojoToMap(ymtCatalogsI),"SQL-YmtCatalogs");
			
			//Mongo
			if (YmtMongoDriverFactroy.isOldMongoCheck()){
				//ProductStockInfo
				Map<String, Object> mongoTgtMap = new HashMap<String,Object>();
				mongoTgtMap.put("ProductId", productId);
				mongoTgtMap.put("CatalogId", catalogId);
				mongoTgtMap.put("Price", price);
				mongoTgtMap.put("NewGuestPrice", newCustomerPrice);
				mongoTgtMap.put("VipPrice", vipPrice);
				mongoTgtMap.put("StockNum", numStock);
				
				AssertService.assertResultEqual(mongoTgtMap,new ProductStockInfoWapper().getByCatalogId(catalogId));
			}
			
			if (YmtMongoDriverFactroy.isNewMongoCheck()){	
				JSONArray CatalogList = new JSONArray(productDetailModelWapper.getProductId(productId).get("CatalogList").toString());
				//System.out.println(CatalogList.toString());
				boolean isFoundCatalog = false;
				for(int k=0;k<CatalogList.length();k++){
					if (CatalogList.isNull(k)){
						Logger.verifyIsNull(CatalogList.get(k), "CatalogList 第["+k+"] 为空");
						break;
					}
					
					
					//获取对应catalogId的数据
				/*	System.out.println(CatalogList.getJSONObject(k).getString("CatalogId").equals(catalogId));
					System.out.println(CatalogList.getJSONObject(k).getString("CatalogId"));
					System.out.println(catalogId);*/
					if (CatalogList.getJSONObject(k).getString("CatalogId").equals(catalogId)){
						//库存
						Logger.verifyEquals(numStock, CatalogList.getJSONObject(k).getJSONArray("StockList").getJSONObject(0).getInt("Stock"), "ProductDetailModel-Stock");
						
						isFoundCatalog = true;
						JSONArray PriceList = CatalogList.getJSONObject(k).getJSONArray("PriceList");
						for(int m=0;m<PriceList.length();m++){
							Double tmpPrice = (double) -1;
							switch(PriceList.getJSONObject(m).getInt("PriceType"))
							{
							//0 原价
							case 0:
								tmpPrice = price;
								break;
							//1 直播新客价
							case 1:
								tmpPrice = newCustomerPrice;
								break;	
							//2  VIP价
							case 2:
								tmpPrice = vipPrice;
								break;
							default:
								break;
							}
							
							if(tmpPrice>0){
								Logger.verifyEquals(tmpPrice, Double.parseDouble(PriceList.getJSONObject(m).getString("Price")), 
											"ProductDetailModel-Price, type["+PriceList.getJSONObject(m).getInt("PriceType")+"]");
							}
						}
						
						
						//Propertys
						JSONArray PropertyList = CatalogList.getJSONObject(k).getJSONArray("PropertyList");
						JSONArray CatalogPropertys = catalogs.getJSONArray("PropertyValues");
						//当有规格名称时，再对比规格数量
						if (!"null".equals(PropertyList.getJSONObject(0).getString("Name")) ) {
							Logger.verifyEquals(CatalogPropertys.length(), PropertyList.length(), "ProductDetailModel- PropertyList size");
						}						
							
						for(int j=0;j<CatalogPropertys.length();j++){
							JSONObject CatalogProperty =  CatalogPropertys.getJSONObject(j);
							String property = CatalogProperty.getString("PropertyName");
							String attributes = CatalogProperty.getJSONArray("PropertyValues").getJSONObject(0).getString("PropertyValue");
							String attributeUrl = CatalogProperty.getJSONArray("PropertyValues").getJSONObject(0).getString("AttributeUrl");
							for (int l=0;l<PropertyList.length();l++){
								if (PropertyList.getJSONObject(l).getString("Name").equals(property)){
									Logger.verifyEquals(property, PropertyList.getJSONObject(l).getString("Name"), "ProductDetailModel - PropertyList Name");
									Logger.verifyEquals(attributes, PropertyList.getJSONObject(l).getString("Value"), "ProductDetailModel - PropertyList Value");
									Logger.verifyEquals(attributeUrl, PropertyList.getJSONObject(l).getString("PicUrl"), "ProductDetailModel - PropertyList PicUrl");
								}
							}
						}
						break;
					}
				}
				Logger.verifyEquals(true, isFoundCatalog, "catalogId ["+catalogId+"] should be exist");
			}
			
			
			
			//set max & min price 
			if (MaxPrice ==-1&&MinPrice==-1){
				MaxPrice = price;
				MinPrice = price;
			}else{
				MaxPrice = (price>MaxPrice)?price:MaxPrice;
				MinPrice = (price<MinPrice)?price:MinPrice;
			}
			
			
		}
		
		// check max & min price 
		if (YmtMongoDriverFactroy.isOldMongoCheck()){
			AssertService.assertResultEqual(MapUtil.hashMap("MaxCatalogPrice", MaxPrice, "MinCatalogPrice", MinPrice), productBasicInfoWapper.getByProductId(productId));
		}
		
		if (YmtMongoDriverFactroy.isNewMongoCheck()){
			AssertService.assertResultEqual(MapUtil.hashMap("MaxCatalogPrice", MaxPrice, "MinCatalogPrice", MinPrice), productDetailModelWapper.getProductId(productId));
			AssertService.assertResultEqual(MapUtil.hashMap("MaxCatalogPrice", MaxPrice, "MinCatalogPrice", MinPrice), new ProductListingModelWapper().getProductId(productId));
			
		}
		
		
		
		
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}